/**
 * 司机管理服务
 * 基于LeanCloud进行司机数据的CRUD操作
 */

import { dataAPI } from '@/http/leancloud';

export interface DriverData {
  objectId?: string;
  driverName: string;
  company: string;
  phone: string;
  idCard: string;
  licenseType: string;
  licenseExpiry: Date;
  qualificationExpiry: Date;
  homeAddress: string;
  emergencyContact: string;
  emergencyPhone: string;
  status: number; // 0空闲 1忙碌 2休息
  remark?: string;
}

export interface VehicleData {
  objectId?: string;
  vehicleNumber: string;
  vehicleType: string;
  driver: string;
  route: string;
  length: number;
  capacity: string;
  loadVolume: string;
  loadWeight: string;
  status: number; // 0空闲 1配载中 2运输中
}

export interface DriverQueryParams {
  driverName?: string;
  phone?: string;
  company?: string;
  status?: number;
  page?: number;
  pageSize?: number;
}

export interface VehicleQueryParams {
  vehicleNumber?: string;
  driver?: string;
  vehicleType?: string;
  status?: number;
  page?: number;
  pageSize?: number;
}

/**
 * 司机服务类
 */
export class DriverService {
  private static readonly CLASS_NAME = 'Driver';

  /**
   * 查询司机列表
   */
  static async getDriverList(params: DriverQueryParams = {}) {
    try {
      const query: any = {};
      
      if (params.driverName) {
        query.driverName = { $regex: params.driverName };
      }
      if (params.phone) {
        query.phone = { $regex: params.phone };
      }
      if (params.company) {
        query.company = { $regex: params.company };
      }
      if (params.status !== undefined) {
        query.status = params.status;
      }

      const data = await dataAPI.query(this.CLASS_NAME, query);
      return {
        success: true,
        data: data.map(this.formatDriverData),
        total: data.length
      };
    } catch (error) {
      console.error('查询司机列表失败:', error);
      return { success: false, error, data: [], total: 0 };
    }
  }

  /**
   * 获取空闲司机列表
   */
  static async getAvailableDrivers() {
    return await this.getDriverList({ status: 0 });
  }

  /**
   * 格式化司机数据
   */
  private static formatDriverData(item: any): DriverData {
    return {
      objectId: item.objectId,
      driverName: item.driverName || '',
      company: item.company || '',
      phone: item.phone || '',
      idCard: item.idCard || '',
      licenseType: item.licenseType || '',
      licenseExpiry: item.licenseExpiry ? new Date(item.licenseExpiry) : new Date(),
      qualificationExpiry: item.qualificationExpiry ? new Date(item.qualificationExpiry) : new Date(),
      homeAddress: item.homeAddress || '',
      emergencyContact: item.emergencyContact || '',
      emergencyPhone: item.emergencyPhone || '',
      status: item.status || 0,
      remark: item.remark || ''
    };
  }

  /**
   * 获取司机状态文本
   */
  static getStatusText(status: number): string {
    const statusMap: { [key: number]: string } = {
      0: '空闲',
      1: '忙碌',
      2: '休息'
    };
    return statusMap[status] || '未知状态';
  }
}

/**
 * 车辆服务类
 */
export class VehicleService {
  private static readonly CLASS_NAME = 'Vehicle';

  /**
   * 查询车辆列表
   */
  static async getVehicleList(params: VehicleQueryParams = {}) {
    try {
      const query: any = {};
      
      if (params.vehicleNumber) {
        query.vehicleNumber = { $regex: params.vehicleNumber };
      }
      if (params.driver) {
        query.driver = { $regex: params.driver };
      }
      if (params.vehicleType) {
        query.vehicleType = params.vehicleType;
      }
      if (params.status !== undefined) {
        query.status = params.status;
      }

      const data = await dataAPI.query(this.CLASS_NAME, query);
      return {
        success: true,
        data: data.map(this.formatVehicleData),
        total: data.length
      };
    } catch (error) {
      console.error('查询车辆列表失败:', error);
      return { success: false, error, data: [], total: 0 };
    }
  }

  /**
   * 获取空闲车辆列表
   */
  static async getAvailableVehicles() {
    return await this.getVehicleList({ status: 0 });
  }

  /**
   * 格式化车辆数据
   */
  private static formatVehicleData(item: any): VehicleData {
    return {
      objectId: item.objectId,
      vehicleNumber: item.vehicleNumber || '',
      vehicleType: item.vehicleType || '',
      driver: item.driver || '',
      route: item.route || '',
      length: item.length || 0,
      capacity: item.capacity || '',
      loadVolume: item.loadVolume || '',
      loadWeight: item.loadWeight || '',
      status: item.status || 0
    };
  }

  /**
   * 获取车辆状态文本
   */
  static getStatusText(status: number): string {
    const statusMap: { [key: number]: string } = {
      0: '空闲',
      1: '配载中',
      2: '运输中'
    };
    return statusMap[status] || '未知状态';
  }

  /**
   * 获取车型选项
   */
  static getVehicleTypes() {
    return [
      { value: 'small_truck', label: '小型货车' },
      { value: 'medium_truck', label: '中型货车' },
      { value: 'large_truck', label: '大型货车' },
      { value: 'container', label: '集装箱' }
    ];
  }
}